package jian.java.net;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 详见 《Java TCP/IP Socket programing》 P12-13
 * 
 * @author Jian
 * 
 */
public class InetAddressExample {

	public static void main(String[] args) {

		try {
			Enumeration<NetworkInterface> interfaceList = NetworkInterface
					.getNetworkInterfaces();
			if (interfaceList == null) {
				System.out.println("--No interfaces found");
			} else {
				while (interfaceList.hasMoreElements()) {
					NetworkInterface netIface = interfaceList.nextElement();
					System.out.println("Interface " + netIface.getName() + ":");
					Enumeration<InetAddress> addressList = netIface
							.getInetAddresses();
					if (!addressList.hasMoreElements()) {
						System.out
								.println("\t(No addresses for this interface)");
					}
					while (addressList.hasMoreElements()) {
						InetAddress address = addressList.nextElement();
						System.out
								.println("\tAddress "
										+ ((address instanceof Inet4Address) ? "(V4)"
												: (address instanceof Inet6Address ? "(V6)"
														: "?")));
						System.out.println(": " + address.getHostAddress());
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}

	}
}
